import { getBy } from "../addons/kv";
import { RouteHandler, first } from "../addons/router";
import { getConfig, getConfigLock } from "../models/config";
import { StatusError } from "itty-router";

export const withAuth: RouteHandler = async ({ query }, { kv }) => {
  query.host = first(query.host);
  query.token = first(query.token);
  const config = await getConfig(kv);
  const token =
    query.host !== undefined
      ? getBy(config.hosts, "id", query.host)?.token
      : config.token;
  if (token === undefined || (token !== "" && token !== query!.token)) {
    throw new StatusError(401, "登录失败：token 不匹配");
  }
};

export const withRoot: RouteHandler = async (request, args) => {
  if (request.query.host !== undefined) {
    throw new StatusError(403, "需要 root 账户登录");
  }
  await withAuth(request, args);
};

export const withHost: RouteHandler = async (request, args) => {
  if (request.query.host === undefined) {
    throw new StatusError(403, "需要 host 账户登录");
  }
  await withAuth(request, args);
};

export const withRootW: RouteHandler = async (request, args) => {
  await withRoot(request, args);
  const { query } = request;
  query.lock = first(query.lock);
  const lock = await getConfigLock(args.kv);
  const locked =
    lock !== null && lock.timestamp < Date.now() && query.lock === lock.value;
  if (!locked) {
    throw new StatusError(403, "未获取锁");
  }
};
